<?php

namespace app\controller;

use app\BaseController;
use app\model\Category as CategoryModel;
use app\Request;
use app\validate\Category as CategoryValidate;


class Category extends BaseController
{

    public function index(Request $request)
    {
        $model = new CategoryModel();
        $param = $request->param();
        try {


         //   $res = $model->with('children')->paginate(10);
            $res = $model->nestedCategories();
            return show(1, $res);
        } catch (\Exception $e) {
            return show(0, $e->getMessage());
        }

    }

    public function add(Request $request)
    {

        $param = $request->param();
        $model = new  CategoryModel;
        try {

            validate(CategoryValidate::class)->scene('add')->check($param);

            $res = $model->save($param);
            if ($res) {
                return show(1, '新增成功');
            } else {
                return show(0, '新增失败');
            }

        } catch (\Exception $e) {
            return show(0, $e->getMessage());
        }

    }

    public function edit(Request $request)
    {
        $param = $request->param();
        $model = new  CategoryModel;
        try {
            validate(CategoryValidate::class)->scene('edit')->check($param);
            $data = $model->where('id', $param['id'])->select();
            $res = $model->save($data);
            if ($res) {
                show(1, '修改成功');
            } else {
                show(0, '修改失败');
            }
        } catch (\Exception $e) {
            return show(0, $e->getMessage());
        }
    }

    //获取一级分类
    public function getClassif()
    {
        $model = new CategoryModel();
        try {
            $list = $model->where('parent_id', 0)->select();
            return show(1, $list);
        } catch (\Exception $e) {
            return show(0, $e->getMessage());
        }


    }


}